package com.molyfun.parents.utils;

import android.text.TextUtils;
import android.util.Log;
import com.molyfun.parents.MFPApplication;
import com.tencent.imsdk.TIMCallBack;
import com.tencent.imsdk.TIMManager;

/**
 * Created by ligang on 2018/1/12 0012.
 */

public class LoginTIMUtil {

    private static LoginTIMUtil instance;

    private static long loginTime;

    public long getLoginTime() {
        return loginTime;
    }

    public void setLoginTime(long loginTime) {
        this.loginTime = loginTime;
    }

    public boolean isLogoutMyAccount(){
        if (loginTime != 0 && (System.currentTimeMillis() - loginTime < 30 * 1000)){
            return false;
        }
        return true;
    }

    public static LoginTIMUtil getInstance() {
        if (instance == null) {
            instance = new LoginTIMUtil();
        }
        if (loginTime == 0){
            loginTime = System.currentTimeMillis();
        }
        return instance;
    }

    public LoginTIMUtil() {
    }

    public void loginTIM(final ILoginTIMCallback callback) {
        String name = null;
        String password = null;
        try {
            name = MFPApplication.getInstance().getUser().getTxuserid();
            password = MFPApplication.getInstance().getUser().getTxusersign();
        } catch (Exception e) {
            return;
        }
        Log.d("loginTIM", "username--->" + name + "\n" + "password----->" + password);
        if (TextUtils.isEmpty(name) || TextUtils.isEmpty(password)) {
            return;
        }
        TIMManager.getInstance().login(name, password, new TIMCallBack() {
            @Override
            public void onError(int i, String s) {
                Log.d("loginTIM", "登录聊天服务器失败！-----" + loginCount);
                Log.d("loginTIM", "code--->" + i + "\n" + "msg----->" + s);
                if (loginCount < 4) {
                    loginTIM(callback);
                    loginCount++;
                } else {
                    //TODO 回调失败
                    if (callback != null) {
                        callback.onError();
                    }
                    loginCount = 0;
                }
            }

            @Override
            public void onSuccess() {
                loginCount = 0;
                Log.d("loginTIM", "登录聊天服务器成功！");
                if (callback != null) {
                    callback.onSuccess();
                }
                Log.d("loginTIM", "login_user--->" + TIMManager.getInstance().getLoginUser());
            }
        });
    }

    public void logout(){
        TIMManager.getInstance().logout(new TIMCallBack() {
            @Override
            public void onError(int i, String s) {

            }

            @Override
            public void onSuccess() {

            }
        });
    }

    private int loginCount = 0;//登录TIM失败 再尝试登录次数计数

    public interface ILoginTIMCallback {
        void onSuccess();

        void onError();
    }

}
